const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const { Captcha } = require('../models');
const svgCaptcha = require('svg-captcha');
const { setKey } = require('../utils/redis');
const { v4: uuidv4 } = require('uuid');
const { failure, success } = require('../utils/responses');

/**
 * 获取验证码
 * GET /captcha
 */
router.get('/', async (req, res) => {
  try {
    //createMathExpr数学验证码
    //create普通验证码

    const captcha = svgCaptcha.createMathExpr({
      size: 4, // 验证码长度
      ignoreChars: '0O1Il9quv', // 验证码字符中排除 0O1Il9quv
      noise: 5, // 干扰线条数量
      color: true, // 是否有颜色，
      width: 100, // 宽
      height: 40, // 高
    });

    const captchaKey = `captcha:${uuidv4()}`;
    /**公司电脑限制不能安装redis，先不用redis */
    await Captcha.create({ id: captchaKey, text: captcha.text });

    // console.log(captcha.text); //结果

    // res.type('svg');
    success({
      res,
      data: {
        captchaId: captchaKey,
        captcha: captcha.data,
      },
    });
    // res.status(200).send(captcha.data);
  } catch (error) {
    failure({ res, error });
  }
});
/**
 * 校验验证码
 * GET /captcha
 */
router.post('/auth', async (req, res) => {
  try {
    const { captchaToken, captchaKey } = req.body;
    const { captchaText } = jwt.verify(captchaToken, captchaKey);
    console.log(captchaText, 'captchaText');

    success({ res, data: captchaText });
  } catch (error) {
    failure({ res, error });
  }
});

module.exports = router;
